#include "dead_code.hpp"

dead_code::dead_code(const CFGvisitorFlatInfo& _flat, const LiveVariable& _lv) 
:	flat(_flat), lv(_lv)
{	
}

set<label_t> dead_code::dead() {
	set<label_t> D;

	for_each(this->flat.labels, [&D, this](CFGvertex* Bell){

		label_t ell = Bell->label();

		ASTvisitorDefs defs_visitor;
		defs_visitor.StartVisit(this->getPayload(Bell));
		set<string> defs = defs_visitor.getDefs();
		
		LV kill = LiveVariable::compute_kill_gen(Bell).second;
		
		if (!defs.empty() && !subset(kill, this->lv.MFP_exit(ell))) {
			D.insert(ell);
		}
	});
	
	return D;
}

ASTnode* dead_code::getPayload(label_t ell0) const {
	return this->getPayload(flat.labels[ell0]);
}

ASTnode* dead_code::getPayload(CFGvertex *n) const {
	ASTnode *a = NULL;
	if (TRY_TYPE(box*, b, n)) {
		a = b->payload;
	}
	if (TRY_TYPE(diamond*, d, n)) {
		a = d->condition;
	}
	assert(a);
	return a;
}
